package com.weifly.weistock.record.asset.impl;

import com.weifly.weistock.core.util.visitor.PreviousVisitor;
import com.weifly.weistock.record.asset.AssetConfigService;
import com.weifly.weistock.record.asset.AssetMonitorService;
import com.weifly.weistock.record.asset.AssetUtils;
import com.weifly.weistock.record.asset.domain.AssetDayDto;
import com.weifly.weistock.record.asset.domain.AssetYearDto;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 用户资产服务实现
 *
 * @author weifly
 * @since 2019/9/17
 */
public class AssetMonitorServiceImpl implements AssetMonitorService {

    private SortedMap<String, AssetYearDto> yearMap = new TreeMap<>(); // key有序的map

    private AssetConfigService assetConfigService;

    public void setAssetConfigService(AssetConfigService assetConfigService) {
        this.assetConfigService = assetConfigService;
    }

    @Override
    public void updateYearList(List<AssetYearDto> yearList) {
        this.yearMap.clear();
        for(AssetYearDto yearDto : yearList){
            this.yearMap.put(yearDto.getYear(), yearDto);
        }
    }

    @Override
    public void updateAsset(AssetDayDto assetDay) {
        if(assetDay==null || StringUtils.isBlank(assetDay.getDay())){
            return;
        }

        // 合并day到year
        String year = assetDay.getDay().substring(0, 4);
        AssetYearDto yearDto = this.yearMap.get(year);
        if(yearDto==null){
            yearDto = new AssetYearDto();
            yearDto.setYear(year);
            this.yearMap.put(year, yearDto);
        }
        AssetUtils.updateDayOfYear(yearDto, assetDay);

        // 写入存储
        this.assetConfigService.saveYear(yearDto);
    }

    @Override
    public List<AssetDayDto> getAssetDayList(String day, int size) {
        List<AssetDayDto> dayList = new ArrayList<>();
        Iterator<AssetDayDto> dayIter = new PreviousVisitor(this.yearMap.values());
        while(dayIter.hasNext()){
            AssetDayDto dayDto = dayIter.next();
            if(StringUtils.isBlank(day) || day.compareTo(dayDto.getDay())>0){
                dayList.add(dayDto);
                if(dayList.size()>size){
                    break;
                }
            }
        }
        return dayList;
    }

    @Override
    public List<AssetDayDto> loadChartDayList(String lowDay) {
        LinkedList<AssetDayDto> dayList = new LinkedList<>();
        if(StringUtils.isBlank(lowDay)){
            return dayList;
        }

        Iterator<AssetDayDto> dayIter = new PreviousVisitor(this.yearMap.values());
        while(dayIter.hasNext()){
            AssetDayDto dayDto = dayIter.next();
            if(lowDay.compareTo(dayDto.getDay())>0){
                break;
            }else{
                dayList.addFirst(dayDto);
            }
        }
        return dayList;
    }
}
